package model;

import main.RandomGenerator;
import main.Simulator;
import event.BackgroundTrafficEvent;
import event.Event;
import event.PacketArrivedAtRouterEvent;

/**
 * Classe que representa o tráfego de fundo.
 */
public class BackgroundTraffic {

	Simulator simulator;
	
	public BackgroundTraffic(Simulator simulator) {
		this.simulator = simulator;
	}
	
	/**
	 * Amostra da distribuição exponencial.
	 * @return
	 */
	public double getExponentialDistributionSample() {
		double sample = RandomGenerator.nextDouble();
		return -Math.log(sample) * simulator.getProperties().getTFinterval();
	}
	
	/**
	 * Amostra da distribuição geométrica.
	 * @return
	 */
	public int getGeometricDistributionSample() {
		double sample = RandomGenerator.nextDouble();
		return (int) Math.ceil(Math.log(sample) / Math.log(1 - (1.0/simulator.getProperties().getTFsize())));
	}
	
	/**
	 * Método que programa o evento de chegada de pacotes de tráfego de fundo no receptor
	 * e agenda o evento da próxima rajada de pacotes.
	 */
	public void sendPackets() {
		double time = simulator.getTime();
		double delay = getExponentialDistributionSample();
		int n = getGeometricDistributionSample();
		
		for (int i = 0; i < n; i++) {
			BackgroundPacket pack = new BackgroundPacket();
			Event event = new PacketArrivedAtRouterEvent(time, pack);
			simulator.addEvent(event);
		}
		
		simulator.addEvent(new BackgroundTrafficEvent(time + delay));
	}
	
}
